package com.devin.dao;

import com.devin.pojo.UserInfo;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

@Mapper
@CacheNamespace(blocking = true,eviction= LruCache.class,flushInterval=0L,size=1024,readWrite = true)
public interface UserMapper {
    @Select(" select * from users")
    @Options(useCache = true)
    List<UserInfo> getUsers();

    @Insert(" insert into users values(null,#{email},#{username},#{password},#{phoneNum},#{status})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void addUser(UserInfo user);

    @Select(" select * from users where id=#{userId}")
    @Results({@Result(id = true,property = "id",column = "id")
            ,@Result(property = "roles",column = "id",javaType = List.class,many = @Many(select ="com.devin.dao.RoleMapper.getRolesByUserId"))
    })
    @Options(useCache=true)
    UserInfo getUserById(Integer userId);

    @Delete(" delete from users_role where userId=#{userId} and roleId=#{roleId}")
    void delRoleByUserId(Integer userId, Integer roleId);

    @Delete(" delete from users_role where userId=#{userId}")
    void delUserAndRoles(Integer userId);

    @Delete(" delete from users where id=#{userId}")
    void delUser(Integer userId);

    @Select(" select * from users where username=#{username}")
    @Results({@Result(id = true,property = "id",column = "id")
            ,@Result(property = "roles",column = "id",javaType = List.class,many=@Many(select = "com.devin.dao.RoleMapper.getRolesByUserId",fetchType = FetchType.EAGER))
    })
    @Options(useCache = true)
    UserInfo getUser(String username);
}
